package org.linlinjava.litemall.core.storage;

import io.minio.*;
import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.core.storage.config.MinioProperties;
import org.springframework.stereotype.Component;
import java.io.InputStream;


@Component
@RequiredArgsConstructor
public class MinioStorage {
    private final MinioClient minioClient;
    private final MinioProperties minioProperties;

    /**
     * 上传文件到 MinIO 并返回访问URL
     *
     * @param objectName  文件名
     * @param inputStream 文件流
     * @return 文件访问URL，上传失败则返回null
     */
    public String uploadFile(String objectName, InputStream inputStream) {
        try {
            // 检查存储桶是否存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .build());
            if (!bucketExists) {
                // 创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .build());
            }
            // 添加img/前缀
            String fullObjectName = "img/" + objectName;
            
            // 上传文件
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(fullObjectName)  // 使用带有img/前缀的文件名
                    .stream(inputStream, inputStream.available(), -1)
                    .build());

            // 返回永久访问URL时也要使用带前缀的文件名
            return String.format("%s/%s/%s",
                    minioProperties.getEndpoint(),
                    minioProperties.getBucketName(),
                    fullObjectName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除文件
     *
     * @param objectName 文件名
     * @return 成功删除返回 true
     */
    public boolean deleteFile(String objectName) {
        try {
            String fullObjectName = "img/" + objectName;
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(fullObjectName)
                    .build());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}